import { removeAllAuthFields } from '@/utils/auth.js';
import { useAuthStore } from '@/stores/index.js';
import { login } from '@/api/auth/signV2.js';
import { getUrlParam } from '@/utils/common.js';
import { menu } from '../../../public/menu';

const loginRoutePath = '/home';
const whiteList = ['/home', '/404', '/webUi'];
export const createNavigationGuards = (router) => {
  // 全局前置守卫
  router.beforeEach((to, from, next) => {
    const auth = useAuthStore();
    const toNext = () => {
      const userInfo = auth.userInfo;
      const isAuthorization = menu.length ? 'fds' : userInfo?.accessToken;
      if (isAuthorization) {
        if ((auth.addRouters.length === 0 && auth.isRequest === false) || menu.length) {
          auth
            .generateRoutes(userInfo.roleId)
            .then(() => {
              const addRouters = auth.addRouters;
              addRouters.forEach((r) => {
                router.addRoute(r);
              });
              const redirect = decodeURIComponent(from.query.redirect || '/');
              console.log('addRouters>>:', addRouters);
              console.log('isIframe>>:', isIframe);
              console.log('to>>:', to);
              if (menu.length) {
                next();
              } else {
                if (to.path === redirect) {
                  next({ ...to, replace: true });
                } else if (isIframe) {
                  // 跳转到目的路由
                  const path = getUrlParam(window.location.href, 'fileName');
                  console.log('path>>:', path);
                  console.log('to.path>>:', to.path);
                  next({ path: to.path });
                } else {
                  // next({ path: redirect });
                  next({ ...to, replace: true });
                }
              }
            })
            .catch((err) => {
              auth.setUserInfo({});
              removeAllAuthFields();
              next(loginRoutePath, { replace: true });

              console.log(err);
              // getSignV2Logout().then(() => {
              //   next({ path: loginRoutePath, query: { redirect: to.fullPath } });
              // });
            });
        } else {
          next();
        }
      } else {
        // 白名单
        if (whiteList.includes(to.path)) {
          next();
        } else {
          removeAllAuthFields();
          next(loginRoutePath, { replace: true });
        }
      }
    };
    const isIframe = to.fullPath.includes('isIframe=true') || '';
    if (isIframe) {
      login().then((res) => {
        auth.setUserInfo(res.data);
        toNext();
      });
    } else {
      toNext();
    }
  });
};
